<?php

namespace app\api\validate\user;

use think\Validate;

class CreatorValidate extends Validate
{
    // 定义验证规则
    protected $rule = [
        'motto' => 'require',       // 简介
        'images' => 'array|imageArray',       // 图片数组验证
        'video' => 'array|videoArray',       // 视频数组验证
        'document_type' => 'in:1,2',                 // document_type 必须是 1 或 2
        'document_images' => 'array|imageArray',       // 证件图片数组验证
    ];


    // 定义验证场景
    protected $scene = [
        'default' => ['images', 'video', 'document_type', 'document_images', "motto"],
    ];

    public function __construct()
    {
        $this->field = [
            'images' => __('images'),
            'video' => __('video'),
            'document_type' => __('document_type'),
            'document_images' => __('document_images'),
            'motto' => __('motto'),
        ];
        $this->message = array_merge($this->message, [
            'images.array' => __('Images must be an array.'),
            'images.imageArray' => __('Each element in images must be a valid image.'),
            'video.array' => __('Video must be an array.'),
            'video.videoArray' => __('Each element in video must be a valid video file.'),
            'document_type.in' => __('Document type must be 1 or 2.'),
            'document_images.array' => __('Document images must be an array.'),
            'document_images.imageArray' => __('Each element in document_images must be a valid image.'),
        ]);
        parent::__construct();
    }

    /**
     * 自定义验证规则 - 检查数组中的每个元素是否是图片
     * @param $value
     * @param $rule
     * @param array $data
     * @param string $field
     * @return bool|string
     */
    protected function imageArray($value, $rule, array $data = [], string $field = ''): bool|string
    {
        foreach ($value as $item) {
            // 使用正则判断文件扩展名是否是图片格式（这里支持 png, jpg, jpeg 等）
            if (image_or_video_extension($item) != "image") {
                return $field . ' should be a valid image file.';
            }

        }
        return true;
    }

    /**
     * 自定义验证规则 - 检查数组中的每个元素是否是视频
     * @param $value
     * @param $rule
     * @param array $data
     * @param string $field
     * @return bool|string
     */
    protected function videoArray($value, $rule, array $data = [], string $field = ''): bool|string
    {
        foreach ($value as $item) {
            // 使用正则判断文件扩展名是否是视频格式（这里支持 mp4, avi, mkv 等）
            if (image_or_video_extension($item) != "video") {
                return $field . ' should be a valid video file.';
            }
        }
        return true;
    }
}